import {  constantRoutes } from '@/router'
//import { asyncRoutes} from '@/router'
import { buildDynamicRouters, buildVisableFilter } from '@/utils/index'
import localStorageUtil from '@/utils/localStorageUtil'
import sessionStorageUtil from '@/utils/sessionStorageUtil'
import Layout from '@/views/layout/Layout'
import dynamicConfig from '@/router/modules/dynamicConfig'


/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }

    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children)
    }
    res.push(tmp)
  })

  return res
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes  异步路由
 */
export function filterDynamicRoutes(routes) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (tmp.component === 'Layout') {
      tmp.component = Layout
      res.push(tmp)
    } else {
      tmp.component = dynamicConfig[tmp.component]
      // tmp.component = _import(tmp.component)
      res.push(tmp)
    }
    if (tmp && tmp.children && tmp.children.length) {
      tmp.children = filterDynamicRoutes(tmp.children)
      console.log("tmp:" + tmp.name)
    }
  })

  return res
}

const permission = {
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    }
  },
  actions: {
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        //let accessedRoutes = null
        const authorities = localStorageUtil.fetch('authorities')
        const visableFilter = buildVisableFilter(authorities)
        localStorageUtil.save('visableFilter', visableFilter)
        let dynamicRouters = buildDynamicRouters(authorities, 'id', 'parentId')
        debugger
        dynamicRouters = filterDynamicRoutes(dynamicRouters)
        debugger
        console.log("GenerateRoutes")
        console.log(dynamicRouters)
        dynamicRouters.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', dynamicRouters)
        sessionStorageUtil.saveObject('BUILD-ROUTES', dynamicRouters);
        commit('SET_AUTHORITIES', dynamicRouters)
        resolve(dynamicRouters)
      })
    },
    SetPermissionRoutes({ commit }) {
      return new Promise(resolve => {
        let dynamicRouters = sessionStorageUtil.fetch('BUILD-ROUTES');
        commit('SET_AUTHORITIES', dynamicRouters)
        resolve(dynamicRouters)
      })
    }
  }
}

export default permission
